package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Album;
import model.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/api/album-list.json")
public class AlbumListApi extends HttpServlet {

    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String keyword = req.getParameter("keyword");
        if(keyword != null&& keyword.trim().isEmpty()){
            keyword = null;
        }
        List<Album> albumList = new ArrayList<>();
        Object result;
        result = new Object(){
            public boolean success = true;
            public Object data = albumList;
        };
        try(Connection c = DBUtil.getConnection()){
            String sql;
            if(keyword==null) {
                sql = "SELECT aid,name,cover,count FROM album ORDER BY aid DESC";
            }else {
                sql = "SELECT aid,name,cover,count FROM album WHERE name LIKE ? ORDER BY aid DESC ";
            }
            try(PreparedStatement s = c.prepareStatement(sql)){
                if(keyword !=null){
                    s.setString(1,"%"+ keyword+ "%");
                }
                try(ResultSet rs = s.executeQuery()){
                    while(rs.next()){
                        Album album = new Album();
                        album.aid = rs.getInt("aid");
                        album.name = rs.getString("name");
                        album.cover = rs.getString("cover");
                        album.count = rs.getInt("count");
                        albumList.add(album);

                    }
                }
            }
        } catch (SQLException exc) {
            //1.打印异常栈，便于找到原因
            exc.printStackTrace();
            result = new Object(){
                public boolean success = false;
                public String reason = exc.getMessage();
            };
        }
String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(result);
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        resp.getWriter().println(json);
    }
    }
